<?php
App::uses('AppController', 'Controller');

class UsersController extends AppController {

/**
 * This controller does not use a model
 *
 * @var array
 */
	public $uses = array('User','Group');
	public $components = array('Paginator');

	public function admin_index(){
		$pagination_settings= array();		
		$pagination_settings['limit'] =30;
		$pagination_settings['conditions']=array('User.is_delete'=>0);
		$this->Paginator->settings =$pagination_settings;
	    $users = $this->Paginator->paginate('User');
	    //var_dump($users);
		$this->set("data",$users);
//		var_dump($this->Session->read('User'));
	}
	public function login() {
		$this->layout=false;
		$post_data = $this->data;
		//var_dump($post_data);
		if(!empty($this->data)){
			$result = $this->User->validateLogin($this->data['Users']);
			//var_dump($result);
			if($result !=false){
				$this->Session->setFlash('Bienvenida '.$result['User']['username'].'!');
                $this->Session->write('User', $result); 
                // Go to our first destination!
                $this->Redirect('/');
			}
		}
	}

	public function admin_add(){
		
		if(!empty($this->data)){
			$this->User->set($this->data);			
			if($this->User->validates()){
				if($this->User->save($this->data)){
					$this->redirect('/admin/users');
				}				
			}
			else{
				$errors = $this->User->validationErrors;
				$this->Session->setFlash(__("Verifique los valores ingresados, algun dato es incorrecto", true), 'flash', array('class' => 'alert alert-error'));
			}
		}


		$groups= $this->Group->find('list');
		$this->set("groups",$groups);
	}

	public function admin_edit($id){

		if (!empty($this->data)){
    	$this->User->id = $id;
      if ($this->User->save($this->data)) {
          $this->Session->setFlash('Cliente Actualizado.', 'flash', array('class' => 'thrill'));
          $this->redirect('/clients');
      }
    }
    else {
        $this->request->data = $this->User->findById($id);
    }
    $groups= $this->Group->find('list');
		$this->set("groups",$groups);
	}

	public function admin_delete($id){
		$this->layout=false;
		$this->render(false);
		//var_dump($id);
		$this->User->id= $id;
		$user=$this->User->read();
		//var_dump($user);
		$user['User']['is_delete']= 1;
		//var_dump($user);
		
		$this->User->save($user);
		$this->redirect('/admin/users');
	}

	public 	function logout(){
		$this->Session->destroy();
	}
}
